package shop.DAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;

import shop.bean.OfferBean;
import shop.util.ConnectionManager;

public class OrderDAO {
	static Connection currentCon = null;
	static ResultSet rs = null; 
	
	//update the quantity of a product to "newQuantity" and stores an order 
	public static void placeOrder(String username, int productId, int stockQuantity, int orderedQuantity){	
		int newQuantity = stockQuantity - orderedQuantity;
		setNewQuantity(productId, newQuantity);
		storeOrder(username, productId, orderedQuantity);
	}

	public static void storeOrder(String username, int productId, int orderedQuantity) {
		//preparing some objects for connection 
				Statement stmt = null; 

				String query = "INSERT INTO orders (ITEM_ID, USER_NAME, QUANTITY) VALUES (" +
								+ productId +", '" + username +"'," + orderedQuantity +")";
				try 
				{
					//connect to DB 
					currentCon = ConnectionManager.getConnection();
					stmt=currentCon.createStatement();
					stmt.execute(query);	        
				} 
				catch (Exception ex) 
				{
					System.out.println("Log In failed: An Exception has occurred! " + ex);
					System.out.println(query);
				} 

				//some exception handling
				finally 
				{
					if (rs != null)	{
						try {
							rs.close();
						} catch (Exception e) {}
						rs = null;
					}

					if (stmt != null) {
						try {
							stmt.close();
						} catch (Exception e) {}
						stmt = null;
					}

					if (currentCon != null) {
						try {
							currentCon.close();
						} catch (Exception e) {
						}

						currentCon = null;
					}
				}

	}

	public static void setNewQuantity(int productId, int newQuantity) {
	//preparing some objects for connection 
		Statement stmt = null; 

		String query = "UPDATE items SET QUANTITY="+ newQuantity +
				" WHERE item_id="+ productId;

		try 
		{
			//connect to DB 
			currentCon = ConnectionManager.getConnection();
			stmt=currentCon.createStatement();
			stmt.execute(query);	        
		} 

		catch (Exception ex) 
		{
			System.out.println("Update Product Quantity failed: An Exception has occurred! " + ex);
			System.out.println(query);
		} 

		//some exception handling
		finally 
		{
			if (rs != null)	{
				try {
					rs.close();
				} catch (Exception e) {}
				rs = null;
			}

			if (stmt != null) {
				try {
					stmt.close();
				} catch (Exception e) {}
				stmt = null;
			}

			if (currentCon != null) {
				try {
					currentCon.close();
				} catch (Exception e) {
				}

				currentCon = null;
			}
		}
	}
}
